package com.example.mybank.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.mybank.entity.Buycount;
import com.example.mybank.entity.Product;
import com.example.mybank.entity.Users;
import com.example.mybank.mapper.BuycountMapper;
import com.example.mybank.tool.MyException;
import com.example.mybank.tool.RedisTool;
import com.example.mybank.tool.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class BuycountService {

    @Autowired
    BuycountMapper buycountMapper;

    @Autowired
    EngineService engineService;

    // 看记录是否已经存在（账户，产品）
    public Buycount getBuycountByProduct(Users users, long productID){

        QueryWrapper<Buycount> qw1 = new QueryWrapper();
        qw1.eq("users", users.getId());
        qw1.eq("product", productID);
        List<Buycount> bcs1 = buycountMapper.selectList(qw1);

        Buycount buycount = bcs1.size() > 0? buycount = bcs1.get(0) : null;

        return buycount;
    }

    // 查询（同用户，同引擎，8小时内）初筛记录
    public Buycount getBuycountByEngine(Users users, Product product) throws MyException {
        List<Buycount> buycounts = buycountMapper.selectByUserEngineInmins(users.getId(), product.getEngine(), 8 * 60);
        Long productID = product.getId();
        Buycount buycount = null;
        if (buycounts.size() > 0) {
            // 存在类似记录
            buycount = new Buycount(users.getId(),  productID,
                    0L, product.getBuy_max(), product.getEngine(),
                    buycounts.get(0).getIs_pass(), buycounts.get(0).getTime_screen());
        } else {
            // 不存在类似记录
            boolean is_pass = engineService.isPass( users, product);
            buycount = new Buycount(users.getId(), productID,
                    0L, product.getBuy_max(), product.getEngine(),
                    is_pass, new Date());
        }

        System.out.println("buycount:"+buycount);


        if (buycountMapper.insert(buycount) == 0) {
            // 插入冲突
            throw new MyException(ResultCode.Buycount_Insert_Conflict);
        }

        return buycount;

    }

}
